import swal from 'sweetalert2';
import { Message } from 'primeng/components/common/api';
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { Http } from '@angular/http';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import 'rxjs/add/operator/switchMap';

import { User } from '../../../core/auth/user.service';
import { CommonService } from '../../../core/common/common.service';
import { ConfigService } from '../../../core/common/config.service';
import { FeeComponent } from '../component/fee/fee.component';
import { NodeComponent } from '../component/node/node.component';
@Component({
  selector: 'app-sale',
  templateUrl: './sale.html',
  styles: [``]
})
export class Sale implements OnInit, AfterViewInit {
  public show = true;
  public previousClick = false;
  public product: any = {};
  public discnt: any = {};
  public discnts: Array<any> = [];
  public backURL = '';
  public nodeInfos: Array<any> = [];
  public customer: any = {};
  public feeValid = false;
  public contract: any = {};
  public submitable = true;
  public msgs: Message[] = [];
  public totalFee = 0;
  @ViewChild('ncloudnode') public ncloudnode: NodeComponent;
  @ViewChild('fee') public fee: FeeComponent;
  constructor(private user: User, private route: ActivatedRoute, private router: Router, private http: Http,
    private config: ConfigService, private common: CommonService, private translate: TranslateService) {
    this.initParameters();
  }
  ngOnInit() {
    this.msgs = [];
    this.translate.get('crm.sale.totalFee').subscribe((res: string) => {
      this.msgs.push({ severity: 'success', summary: res, detail: this.totalFee + '' });
    });
  }
  ngAfterViewInit() {
    this.initNodeInfos();
  }
  private initNodeInfos(): void {
    switch (this.discnt.discntType) {
      case '0':
        break;
      case '1':
        (this.discnt.compCount || []).forEach((c: any) => {
          for (let i = 0; i < c.count; i++) {
            const node: any = {};
            node.modifyTag = '1';
            node.bandWidth = c.bandWidth;
            node.active = true;
            node.nodeName = '新节点 ' + c.bandWidth + 'M';
            node.nodeType = c.nodeType;
            node.isp = { wan: {}, lan: { accessType: '1' } };
            node.equip = {};
            node.cloud = { ipseg: [{}] };
            node.effFlag = '1';
            node.discntType = '1';
            node.discntId = this.discnt.discntId;
            node.billingCycle = this.discnt.billingCycle;
            node.cycleUnit = this.discnt.cycleUnit;
            node.disabledAttr = 'bandWidth,billingCycle';
            this.nodeInfos.push(node);
          }
        });
        this.discnts.push(this.discnt);
        this.calculated();
        break;
      case '2':
        this.ncloudnode.discnt = this.discnt;
        break;
    }
  }
  private initParameters(): void {
    this.route.params.switchMap((params: Params) => {
      const result: any = [];
      if (params['product']) {
        this.product = JSON.parse(params['product']);
      }
      if (params['discnt']) {
        this.discnt = JSON.parse(params['discnt']);
        this.discnt.modifyTag = '1';
      }
      if (params['backURL']) {
        this.backURL = params['backURL'];
      }
      return result;
    }
    ).subscribe((c: any) => { });
  }
  customerSelected($event): void {

  }
  public cancel(): void {
    const array = ['crm.sale.cancel.title', 'crm.sale.cancel.text', 'crm.sale.cancel.confirm', 'crm.sale.cancel.cancel'];

    this.translate.get(array).subscribe((res: string) => {
      swal({
        title: res['crm.sale.cancel.title'],
        text: res['crm.sale.cancel.text'],
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: res['crm.sale.cancel.confirm'],
        cancelButtonText: res['crm.sale.cancel.cancel'],
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger'
      }).then((e: any) => {
        this.back2product();
      }, (dismiss: any) => {
        // dismiss can be 'cancel', 'overlay',
        // 'close', and 'timer'
      });
    });
  }
  private back2product(): void {
    this.router.navigate([this.backURL]);
  }
  public gotopay(): void {
    if (this.check()) {
      this.generateFee();
      this.show = false;
    }

  }
  private check(): boolean {
    if (!this.customer.valForm.valid) {
      this.translate.get('crm.sale.error.customer').subscribe((res: string) => {
        swal({
          text: res,
          showConfirmButton: true
        }).catch(swal.noop);
      });
      return false;
    }
    if (this.ncloudnode.data.length === 0) {
      this.translate.get('crm.sale.error.noneNode').subscribe((res: string) => {
        swal({
          text: res,
          showConfirmButton: true
        }).catch(swal.noop);
      });
      return false;
    }
    if (!this.ncloudnode.valForm.valid) {
      this.translate.get('crm.sale.error.node').subscribe((res: string) => {
        swal({
          text: res,
          showConfirmButton: true
        }).catch(swal.noop);
      });
      return false;
    }
    if (!this.checkcloud()) {
      this.translate.get('crm.sale.error.cloud').subscribe((res: string) => {
        swal({
          text: res,
          showConfirmButton: true
        }).catch(swal.noop);
      });
      return false;
    }
    return true;
  }
  private checkcloud(): boolean {
    let a = true;
    let b = true;
    let c = 0;
    this.ncloudnode.data.forEach((n: any) => {
      if (n.nodeType === 0 && a) {
        a = false;
        c += 1;
      }
      if (n.nodeType === 1 && b) {
        b = false;
        c += 3;
      }
    });
    return c % 4 === 0 || c % 4 === 3 ? true : false;
  }
  public previous(): void {
    this.fee.reset();
    this.show = true;
    this.previousClick = true;
  }
  public fileUploaded(filePath: string): void {
    this.contract.modifyTag = '1';
    this.contract.filePath = filePath;
  }
  public noFileUploaded(): void {
    this.contract = {};
  }
  public submit(): void {
    this.submitable = false;
    const orderInfo: any = {};
    orderInfo.CUSTOMER = this.customer;
    orderInfo.ORDER = this.generateOrder();
    orderInfo.PRODUCT = this.generateProduct();
    orderInfo.DISCNT = this.discnts;
    orderInfo.NODE = this.nodeInfos;
    if (JSON.stringify(this.contract) !== '{}') {
      orderInfo.CONTRACT = [this.contract];
    }
    const newInfo: any = {};
    this.common.copy(newInfo, orderInfo);
    this.common.clearFormGroup(newInfo);
    const url = this.config.get('url') + '?service=OrderService&method=receiveOrderInfo';
    this.http.post(url, newInfo).toPromise().then((resp: any) => {
      const json = resp.json();
      if (json.code === '0000') {
        this.submitable = true;
        const array = ['crm.sale.submit.success.title', 'crm.sale.submit.success.text', 'crm.sale.submit.success.confirm'];
        this.translate.get(array, { contactEmail: this.customer.contactEmail }).subscribe((res: string) => {
          swal({
            title: res['crm.sale.submit.success.title'],
            text: res['crm.sale.submit.success.text'],
            type: 'success',
            timer: 3000,
            confirmButtonColor: '#3085d6',
            confirmButtonText: res['crm.sale.submit.success.confirm'],
            confirmButtonClass: 'btn btn-success',
            buttonsStyling: false
          }).then((e: any) => {
            this.back2product();
          }, (dismiss: any) => {
            // dismiss can be 'cancel', 'overlay',
            // 'close', and 'timer'
            this.back2product();
          });
        });

      } else {
        this.submitable = true;
        this.translate.get('crm.sale.submit.failed.warning').subscribe((res: string) => {
          swal(res, json.message, 'warning');
        });
      }
    });
  }
  private generateProduct(): any {
    const orderProduct: any = {};
    orderProduct.modifyTag = '1';
    orderProduct.prodId = this.product.prodId;
    orderProduct.prodName = this.product.prodName;
    orderProduct.custId = this.customer.custId || '';
    return orderProduct;
  }
  private generateOrder(): any {
    const order: any = {};
    order.custId = this.customer.custId;
    order.prodId = this.product.prodId;
    order.orderType = '10';
    return order;
  }
  private generateFee() {
    this.discnts.forEach((d: any) => {
      switch (d.discntType) {
        case '0':
          this.ncloudnode.data.forEach((n: any) => {
            if (d.index === n.index) {
              d.prodName = this.product.prodName;
              d.billingCycle = n.billingCycle;
              d.discntNameShow = d.discntName + '--' + n.nodeTypeName + ' -- ' + n.nodeName + ' -- ' + n.bandWidth + 'M';
              d.standard = n.standard;
              d.balance = n.balance;
              if (d.standard === 0) {
                d.receiveFee = 0;
                d.payFee = 0;
              } else {
                this.translate.get('crm.sale.fee.input').subscribe((res: string) => {
                  d.receiveFee = res;
                });
                d.payFee = '';
              }
            }
          });
          break;
        case '1':
          d.prodName = this.product.prodName;
          d.discntNameShow = d.discntName;
          d.standard = d.maxFee / 100;
          d.balance = d.minFee / 100;
          d.receiveFee = d.standard;
          d.payFee = d.standard;
          this.feeValid = true;
          break;
        case '2':
          d.prodName = this.product.prodName;
          d.discntNameShow = d.discntName;
          this.ncloudnode.data.forEach((n: any) => {
            if (d.index === n.index) {
              d.prodName = this.product.prodName;
              d.billingCycle = n.billingCycle;
              d.discntNameShow = d.discntName + '--' + n.nodeTypeName + ' -- ' + n.nodeName + ' -- ' + n.bandWidth + 'M';
              //              标准费用
              d.standard = n.standard;
              //              折扣费用
              d.balance = n.balance;
              //              应收费用
              d.receiveFee = d.standard;
              //              实收费用
              d.payFee = d.standard;
            }
          });
          this.feeValid = true;
          break;
      }
    });
  }
  public addDiscnt($event: any): void {
    $event.modifyTag = '1';
    this.discnts.push($event);
  }
  private calculated($event?: number): void {
    this.totalFee = 0;
    this.msgs = [];
    this.translate.get('crm.sale.totalFee').subscribe((res: string) => {
      this.discnts.forEach((d: any) => {
        switch (d.discntType) {
          case '0':
            this.ncloudnode.data.forEach((n: any) => {
              if (d.index === n.index) {
                d.standard = n.standard;
                d.balance = n.balance;
              }
            });
            break;
          case '1':
            d.standard = d.maxFee / 100;
            d.balance = d.minFee / 100;
            break;
          case '2':
            this.ncloudnode.data.forEach((n: any) => {
              if (d.index === n.index) {
                d.standard = n.standard;
                d.balance = n.balance;
              }
            });
            this.feeValid = true;
            break;
        }
        this.totalFee += d.standard ? d.standard : 0;
      });
      this.msgs.push({ severity: 'success', summary: res, detail: this.totalFee + '' });
    });
  }
  public deleteDiscnt($event: any): void {
    let t: any;
    this.discnts.forEach((n: any) => {
      if (n.index === $event) {
        t = n;
      }
    });
    if (t) {
      const idx = this.discnts.indexOf(t);
      this.discnts.splice(idx, 1);
    }
    this.calculated();
  }
}
